'''
Case Type： 数据库系统
Case Name： 事务未提交或回滚，重启集群
Create At:  2020/06/30
Owner    :  @li-xin12345
Descption:  1.开启事务2.事务未提交或回滚，重启集群；3.验证事务是否回滚

history：
created： 2020/06/30  created by @li-xin12345
'''

import os
import unittest
import time
import _thread
import queue
from yat.test import Node
from testcase.utils.CommonSH import *
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *

from testcase.utils.Constant import Constant


class PortOccupied(unittest.TestCase):
    sh_primy = CommonSH('PrimaryDbUser')
    sh_stadb = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case105.py start------------')
        self.rootNode = Node('PrimaryRoot')
        self.primaryNode = Node(node='PrimaryDbUser')
        self.SOURCE_PATH = macro.DB_ENV_PATH
        self.DN1_PATH = macro.DB_INSTANCE_PATH
        self.Constant = Constant()

    def test_set_tran(self):
        # 开启事务并执行一个事务，不做提交
        self.log.info('------------------开启事务并执行一个事务，不做提交------------------------------')
        sql_cmd = '''start transaction;
                     drop table if exists test_zl;
                     create table test_zl(a tinyint,b tinyint,c integer,d bigint);'''
        self.log.info(sql_cmd)
        tr_msg = self.sh_primy.executDbSql(sql_cmd)
        self.log.info(tr_msg)
        res1 = tr_msg.find(self.Constant.TABLE_CREATE_SUCCESS) > -1
        self.assertTrue(res1)

        # 重启后验证事务是否回滚
        self.log.info('------------------重启后验证事务是否回滚------------------------------')
        q_cmd = f'''select * from test_zl1;'''
        self.log.info(q_cmd)
        hq_msg = self.sh_primy.executDbSql(q_cmd)
        self.log.info(hq_msg)
        self.log.info('Successful Reboot')
        res3 = hq_msg.find(self.Constant.NOT_EXIST) > -1
        self.assertTrue(res3)

    def tearDownTestCase(self):
        self.log.info('----------------------------后置处理-----------------------------')
        try:
            db_status = self.sh_primy.getDbClusterStatus('status')
            self.log.info(db_status)
            if db_status:
                pass
            else:
                is_started = self.sh_primy.startDbCluster()

                self.assertTrue(is_started)
                self.log.info(f'{is_started}')
                self.log.info(f'db_status: {is_started}')
        finally:
            sql_cmd = 'drop table if exists test_zl;'
            self.log.info(sql_cmd)
            gres_msg = self.sh_primy.executDbSql(sql_cmd)
            self.log.info(gres_msg)
        self.log.info('------------------reliability_dbsys105 执行完成------------------------------')
